package com.workspace.js_website.controller;

import com.workspace.js_website.bean.User;
import com.workspace.js_website.service.FileService;
import com.workspace.js_website.service.LogService;
import com.workspace.js_website.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 文件下载相关控制
 */

@CrossOrigin
@RestController
public class FileManagerController {

    private final FileService fileService;
    private final LogService logService;

    @Autowired
    public FileManagerController(FileService fileService, LogService logService) {
        this.fileService = fileService;
        this.logService = logService;
    }

    @GetMapping("/download/{filename}")
    public ResponseEntity<InputStreamResource> getFile(@PathVariable("filename") String filename, HttpServletRequest request) throws IOException {
        User currentUser = Util.getCurrentUser();
        String behavior = "requestProduct-" + filename;
        //记录用户访问的资源情况
        logService.addLog(currentUser.getId(), behavior, request.getRemoteAddr());
        String filePath = "D:/lsn/jszx_resource/CoreProduct/" + filename + ".rar";
        return fileService.downloadFile(filePath);
    }
}
